package com.walker.kuyun.ui.component

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.pow
import kotlin.math.sqrt

class ScoreImageView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(
    context!!, attrs, defStyleAttr
) {
    private var score = 0.0f
    private val COLOR_SEG_LIMIT = 255
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textBounds = Rect()
    private val CIRCLE_RADIUS = 58f;

    fun setScore(score: Float?) {
        if (score == null) this.score = 0.0f
        else {
            this.score = score
        }
        invalidate()
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //draw score
        var alphaSeg = (50 + COLOR_SEG_LIMIT * score / 10).toInt()
        if (alphaSeg > COLOR_SEG_LIMIT) {
            alphaSeg = COLOR_SEG_LIMIT
        }
        val argb = Color.argb(alphaSeg, 175, 0, 0)
        @SuppressLint("DefaultLocale") val scoreText = String.format("%.1f", score)
        paint.color = argb
        canvas.drawCircle(width.toFloat(), 0f, CIRCLE_RADIUS, paint)
        paint.color = Color.WHITE
        paint.textSize = 24f
        paint.getTextBounds(scoreText, 0, scoreText.length, textBounds)
        val textHeight = textBounds.height()
        val textWidth = textBounds.width()


        val Y1: Double = (CIRCLE_RADIUS - textHeight) * 1.0 / 2 - 8
        val XX: Double = sqrt((CIRCLE_RADIUS * 1.0).pow(2.0) - (textHeight + Y1).pow(2.0))
        val X1: Double = (XX - textWidth) / 2
        canvas.drawText(
            scoreText,
            width - X1.toFloat() - textWidth,
            (Y1 + textHeight).toFloat(),
            paint
        )
    }
}